<template>
  <div id="history">
    <div
      :class="item.name === $route.name ? 'isActive' : ''"
      class="history-item"
      v-for="(item, index) in routeHistory"
      :key="item.name"
      @click="routeTo(item)"
    >
      {{ item.meta.title }}
      <i
        @click.stop="deleteHistory(index)"
        v-if="routeHistory.length > 1"
        class="el-icon-circle-close ml-3"
      />
    </div>
  </div>
</template>

<script>
import menus from "@/router/menu";
export default {
  watch: {
    $route: {
      immediate: true,
      handler: "addHistory"
    }
  },
  data() {
    return {
      routeHistory: [],
      maxLength: 10, // 最多保存多少条
      menuInfo: {}
    };
  },
  methods: {
    // 添加历史记录
    addHistory(val) {
      let canAdd = true;
      // 判断是否已在记录中
      this.routeHistory.forEach(item => {
        if (item.name === val.name) {
          canAdd = false;
        }
      });
      // 添加记录
      if (canAdd && val.meta.title) {
        const routeObj = {
          name: val.name,
          meta: JSON.parse(JSON.stringify(val.meta))
        };
        if (routeObj.meta.title.includes("menu-")) {
          this.menuInfo = {};
          const name = routeObj.meta.title.split("menu-")[1];
          this.getMenuByName(menus, name);
          routeObj.meta.title = this.menuInfo.title;
        }
        this.routeHistory.push(routeObj);
      }
      // 大于最大条数删除第一条
      if (this.routeHistory.length > this.maxLength) {
        this.routeHistory.shift();
      }
    },
    // 删除历史记录
    deleteHistory(index) {
      this.routeHistory.splice(index, 1);
      const lastName = this.routeHistory[this.routeHistory.length - 1].name;
      if (lastName === this.$route.name) return;
      this.$router.push({ name: lastName });
    },
    // 跳转
    routeTo(item) {
      if (item.name === this.$route.name) return;
      this.$router.push({ name: item.name });
    },
    // 通过 name 获取当前 menu
    getMenuByName(menus, name) {
      let keepOn = true;
      menus.forEach(item => {
        if (item.name === name) {
          this.menuInfo = item;
          keepOn = false;
        }
        if (item.children && item.children.length && keepOn) {
          this.getMenuByName(item.children, name);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
#history {
  height: 34px;
  box-shadow: 0 1px 4px $default-shadow;
  float: left;
  width: 100%;
  box-sizing: border-box;
  padding-left: 15px;
}
.history-item {
  height: 26px;
  @include v-center;
  margin-right: 7px;
  box-sizing: border-box;
  border: 1px solid $default-border;
  padding: 0 10px;
  font-size: $font-12;
  line-height: 24px;
  cursor: pointer;
  user-select: none;
}
.isActive {
  background-color: $primary;
  color: $default-light;
}
</style>
